package com.example.zookeeper;

import lombok.SneakyThrows;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * @ClassName ZooKeeper
 * @Author 小坏
 * @Date 2021/8/19、0:09
 * @Version 1.0
 */
public class zkClient {
    // 注意：逗号前后不能有空格
    private static String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    private static int sessionTimeout = 2000;

    private ZooKeeper zKClient;

    //    @Test
    @Before
    public void init() throws Exception {
        zKClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @SneakyThrows
            @Override
            public void process(WatchedEvent event) {

                System.out.println("-------------------------------");
                List<String> children = zKClient.getChildren("/", true);
                for (String child : children) {
                    System.out.println(child);
                }
                System.out.println("-------------------------------");
            }
        });
    }


    /**
     * 创建文件
     *
     * @throws KeeperException
     * @throws InterruptedException
     */

    @Test
    public void create() throws KeeperException, InterruptedException {
        /**
         * OPEN_ACL_UNSAFE 允许任何人都可以访问
         * CreateMode.EPHEMERAL  临时
         *  CreateMode.PERSISTENT 持久
         *
         */
        String s = zKClient.create("/sanguo", "zhaoyun".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(s);
    }

    /**
     * 获取跟目录所有的节点 和监听创建
     *
     * @throws KeeperException
     * @throws InterruptedException
     */

    @Test
    public void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zKClient.getChildren("/", true);

        for (String child : children) {
            System.out.println(child);
        }

        Thread.sleep(Long.MAX_VALUE);
    }


    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat exists = zKClient.exists("/1", false);
        System.out.println(exists == null ? "not exists" : "exists");


    }

}

